<template>
	<div class="system-gen-container layout-padding">
		<div class="system-gen-padding layout-padding-auto layout-padding-view">
			<div class="system-gen-search">
				<el-row :gutter="20">
					<el-col :span="24" class="col-center" v-auths="['tool:gen:query']">
						<el-input size="default" placeholder="请输入表名称" v-model="state.tableData.param.tableName"
							class="mt10"></el-input>
						<el-input size="default" placeholder="请输入表描述" v-model="state.tableData.param.tableComment"
							class="mt10"></el-input>
						<el-date-picker v-model="state.tableData.dateRange" type="daterange" range-separator="至"
							start-placeholder="开始时间" end-placeholder="结束时间" size="default" class="mt10"
							style="max-width: 250px;" />
						<el-button size="default" class="mt10" type="primary" @click="getTableData()">
							<el-icon>
								<ele-Search />
							</el-icon>
							搜索
						</el-button>
						<el-button size="default" class="mt10" type="info" @click="resetParamData()">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
					<el-col :span="24">
						<el-button size="default" class="mt10" type="success" @click="handleGenTable"
							v-auths="['tool:gen:code']">
							<el-icon>
								<ele-Plus />
							</el-icon>
							生成
						</el-button>
						<el-button size="default" class="mt10" type="primary" plain @click="handleImport"
							v-auths="['tool:gen:import']">
							<el-icon>
								<ele-Upload />
							</el-icon>
							导入
						</el-button>
						<el-button size="default" class="mt10" type="warning" plain @click="handleEditTable"
							v-auths="['tool:gen:edit']">
							<el-icon>
								<ele-Edit />
							</el-icon>
							修改
						</el-button>
						<el-button size="default" class="mt10" type="danger" plain @click="handleDelete"
							v-auths="['tool:gen:remove']">
							<el-icon>
								<ele-Delete />
							</el-icon>
							删除
						</el-button>
					</el-col>
				</el-row>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%"
				ref="multipleTableRef" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" />
				<el-table-column type="index" label="序号" width="80" />
				<el-table-column label="ID" align="center" width="100" prop="tableId" show-overflow-tooltip />
				<el-table-column label="表名称" align="center" prop="tableName" show-overflow-tooltip />
				<el-table-column label="表描述" align="center" prop="tableComment" show-overflow-tooltip />
				<el-table-column label="实体" align="center" prop="className" show-overflow-tooltip />
				<el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip />
				<el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip />
				<el-table-column label="操作" width="150" fixed="right" v-auths="['tool:gen:preview','tool:gen:edit','tool:gen:remove','tool:gen:code']">
					<template #default="scope">
						<el-tooltip content="预览" placement="top">
							<el-button link type="primary" @click="handlePreview(scope.row)" v-auths="['tool:gen:preview']">
								<el-icon>
									<ele-View />
								</el-icon>
							</el-button>
						</el-tooltip>
						<el-tooltip content="编辑" placement="top">
							<el-button link type="primary" @click="handleEditTable(scope.row)" v-auths="['tool:gen:edit']">
								<el-icon>
									<ele-Edit />
								</el-icon>
							</el-button>
						</el-tooltip>
						<el-tooltip content="删除" placement="top">
							<el-button link type="primary" @click="handleDelete(scope.row)" v-auths="['tool:gen:remove']">
								<el-icon>
									<ele-Delete />
								</el-icon>
							</el-button>
						</el-tooltip>
						<el-tooltip content="同步" placement="top">
							<el-button link type="primary" @click="handleSynchDb(scope.row)" v-auths="['tool:gen:edit']">
								<el-icon>
									<ele-Refresh />
								</el-icon>
							</el-button>
						</el-tooltip>
						<el-tooltip content="生成代码" placement="top">
							<el-button link type="primary" @click="handleGenTable(scope.row)" v-auths="['tool:gen:code']">
								<el-icon>
									<ele-Download />
								</el-icon>
							</el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange"
				class="mt15 paginationFlex" :pager-count="5" :page-sizes="[10, 20, 30]"
				v-model:current-page="state.tableData.param.pageNum" background
				v-model:page-size="state.tableData.param.pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total">
			</el-pagination>
		</div>
		<!-- 预览界面 -->
		<el-dialog :title="state.preview.title" v-model="state.preview.open"
			style="width: 90%; height: 90%;max-width: 900px">
			<el-tabs v-model="state.preview.activeName">
				<el-tab-pane v-for="(value, key) in state.preview.data"
					:label="(key as string).substring((key as string).lastIndexOf('/') + 1, (key as string).indexOf('.vm'))"
					:name="(key as string).substring((key as string).lastIndexOf('/') + 1, (key as string).indexOf('.vm'))"
					:key="value">
					<Editor :text="'```' + handleType(key)
						+ '\n' + value + '\n```'" :mode="'preview'" />
				</el-tab-pane>
			</el-tabs>
		</el-dialog>
		<GenDialog ref="genDialogRef" @refresh="getTableData()" />
	</div>
</template>

<script setup lang="ts" name="toolGen">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage, dayjs, ElTable } from 'element-plus';
import { useGenApi } from '/@/api/tool/gen';
import { zip } from '/@/utils/tool';
import router from '/@/router';
// 引入组件
const Editor = defineAsyncComponent(() => import('/@/components/editor/index.vue'));
// 引入组件
const GenDialog = defineAsyncComponent(() => import('/@/views/tool/gen/dialog.vue'));

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<RowUserType[]>([])

// 定义变量内容
const genDialogRef = ref();

const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		dateRange: [], // 时间范围
		param: {
			pageNum: 1,
			pageSize: 10,
			tableName: undefined,
			tableComment: undefined,
			dataName: "master"
		},
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '导入数据库表',
		submitTxt: '确定',
	},
	preview: {
		open: false,
		title: "代码预览",
		data: {},
		activeName: "domain.java"
	}
});
localStorage.setItem("dataName", state.tableData.param.dataName)

// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
	let param = {};
	if (state.tableData.dateRange && state.tableData.dateRange.length > 0) {
		param = {
			...state.tableData.param,
			'params[beginTime]': dayjs(state.tableData.dateRange[0]).format('YYYY-MM-DD'),
			'params[endTime]': dayjs(state.tableData.dateRange[1]).format('YYYY-MM-DD')
		};
	} else {
		param = { ...state.tableData.param };
	}
	useGenApi()
		.listTable(param)
		.then((res) => {
			if (res.code === 200) {
				state.tableData.data = res.rows;
				state.tableData.total = res.total;
			} else {
				ElMessage.error(res.msg);
			}
		}).finally(() => {
			state.tableData.loading = false;
		});
};


/**
 * 多选
 */
const handleSelectionChange = (val: RowUserType[]) => {
	multipleSelection.value = val
}

/**
 * 生成功能
**/
const handleGenTable = (row: RowGenType) => {
	const tbNames = row.tableName || multipleSelection.value.map(item => item.tableName);
	if (tbNames == "") {
		ElMessage.error("请选择要生成的数据");
		return;
	}
	//选择下载方式
	ElMessageBox.confirm("请选择下载方式", "提示", {
		confirmButtonText: "自定义路径",
		cancelButtonText: "打包下载",
		type: "warning",
	}).then(() => {
		useGenApi().genCode(row.tableName).then(response => {
			if (response.code === 200) {
				ElMessage.success("成功生成到自定义路径：" + row.genPath);
			} else {
				ElMessage.error(response.msg);
			}
		});
	}).catch(() => {
		zip('/tool/gen/batchGenCode?tables=' + tbNames, new Date().getTime() + ".zip")
	});
}

/**
 * 修改
 * */
const handleEditTable = (row: RowGenType) => {
	const tableId = row.tableId || multipleSelection.value.map(item => item.tableId).join(",");
	if (tableId == "") {
		ElMessage.error("请选择要生成的数据");
		return;
	}
	router.push({ path: "/editTable", query: { tableId: tableId } });
}

/**
 * 删除
 * */
const handleDelete = (row: RowGenType) => {
	const tbNames = row.tableId || multipleSelection.value.map(item => item.tableId).join(",");
	if (tbNames == "") {
		ElMessage.error("请选择要生成的数据");
		return;
	}
	ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		useGenApi().delTable(tbNames).then(response => {
			if (response.code === 200) {
				ElMessage.success("删除成功");
				getTableData();
			} else {
				ElMessage.error(response.msg);
			}
		});
	}).catch(() => {
		ElMessage.info('已取消删除');
	});
}

/**
 * 预览
 * **/
const handlePreview = (row: RowGenType) => {
	const tbNames = row.tableId || multipleSelection.value.map(item => item.tableId).join(",");
	if (tbNames == "") {
		ElMessage.error("请选择要生成的数据");
		return;
	}
	useGenApi().previewTable(tbNames).then(response => {
		if (response.code === 200) {
			state.preview.data = response.data;
			state.preview.open = true;
			state.preview.activeName = "domain.java";
		} else {
			ElMessage.error(response.msg);
		}
	});
}

/**
 * 获取文件类型
 * */
const handleType = (key: string) => {
	const dataType = key.match(/\.(\w+)(\.vm)?$/)?.[1]
	if (dataType?.includes('vm')) {
		return key.match(/[^/]+(?=\.vm$)/)?.[0];
	} else if (dataType === 'vue') {
		return 'js'
	} else {
		return dataType
	}
}


/**
 * 同步代码
 * **/
const handleSynchDb = (row: RowGenType) => {
	const tbNames = row.tableName || multipleSelection.value.map(item => item.tableName).join(",");
	if (tbNames == "") {
		ElMessage.error("请选择要生成的数据");
		return;
	}
	useGenApi().synchDb(tbNames).then(response => {
		if (response.code === 200) {
			ElMessage.success("同步成功");
		} else {
			ElMessage.error(response.msg);
		}
	});
}


/** 导入按钮操作 */
const handleImport = () => {
	genDialogRef.value.openDialog();
}

/**
 *  重置搜索条件
 */
const resetParamData = () => {
	state.tableData.param = {
		pageNum: 1,
		pageSize: 10,
		tableName: undefined,
		tableComment: undefined,
		dataName: "master"
	};
	getTableData();
};



// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.pageSize = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.pageNum = val;
	getTableData();
};
// 页面加载时
onMounted(() => {
	getTableData();
});
</script>

<style scoped lang="scss">
.system-gen-container {
	.system-gen-padding {
		padding: 15px;

		.el-table {
			flex: 1;
		}
	}
}

.mt10 {
	max-width: 140px;
	margin: 10px 0 10px 10px;
}
</style>
